.TH std::basic_string::size, 3 "2024.06.10" "http://cppreference.com" "C++ Standard Libary"
.SH NAME
std::basic_string::size, \- std::basic_string::size,

.SH Synopsis

   size_type size() const;   \fB(1)\fP (noexcept since C++11)
                                 (constexpr since C++20)
   size_type length() const; \fB(2)\fP (noexcept since C++11)
                                 (constexpr since C++20)

   Returns the number of CharT elements in the string, i.e. std::distance(begin(),
   end()).

.SH Parameters

   \fI(none)\fP

.SH Return value

   The number of CharT elements in the string.

.SH Complexity

   Unspecified \fI(until C++11)\fP
   Constant    \fI(since C++11)\fP

.SH Notes

   For std::string, the elements are bytes (objects of type char), which are not the
   same as characters if a multibyte encoding such as UTF-8 is used.

.SH Example


// Run this code

 #include <cassert>
 #include <iterator>
 #include <string>

 int main()
 {
     std::string s("Exemplar");
     assert(8 == s.size());
     assert(s.size() == s.length());
     assert(s.size() == static_cast<std::string::size_type>(
         std::distance(s.begin(), s.end())));

     std::u32string a(U"ハロー・ワールド"); // 8 code points
     assert(8 == a.size()); // 8 code units in UTF-32

     std::u16string b(u"ハロー・ワールド"); // 8 code points
     assert(8 == b.size()); // 8 code units in UTF-16

     std::string c("ハロー・ワールド"); // 8 code points
     assert(24 == c.size()); // 24 code units in UTF-8

     #if __cplusplus >= 202002
     std::u8string d(u8"ハロー・ワールド"); // 8 code points
     assert(24 == d.size()); // 24 code units in UTF-8
     #endif
 }

.SH See also

   empty    checks whether the string is empty
            \fI(public member function)\fP
   max_size returns the maximum number of characters
            \fI(public member function)\fP
   size     returns the number of characters
   length   \fI(public member function of std::basic_string_view<CharT,Traits>)\fP
